package ycl.common.config;

import com.alibaba.nacos.shaded.com.google.common.collect.Lists;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;
import ycl.common.constants.SecurityConstant;

import java.util.ArrayList;
import java.util.List;

/**
 * @author YCL
 * @date 2022/03/04 15:22:43
 */
@Configuration
@EnableSwagger2WebMvc
public class SwaggerConfig {



	//配置swagger的Docket的bean实例
	@Bean
	public Docket docket() {
		return new Docket(DocumentationType.SWAGGER_2)
				.apiInfo(apiInfo())
				.select()
				.apis(RequestHandlerSelectors.any())
				.paths(PathSelectors.any())
				.paths(PathSelectors.regex("(?!/health).*"))
				.paths(PathSelectors.regex("(?!/error).*"))
				.paths(PathSelectors.regex("(?!/actuator).*"))
				.build()
				.securitySchemes(securitySchemes())
				.securityContexts(securityContexts());
	}

	private List<SecurityContext> securityContexts() {
		ArrayList<SecurityContext> list = Lists.newArrayList();
		SecurityContext build = SecurityContext.builder()
				.securityReferences(securityReferences())
				.build();
		list.add(build);
		return list;
	}

	/**
	 * 全局认证
	 *
	 * @return 认证列表
	 */
	private List<SecurityReference> securityReferences() {
		AuthorizationScope scope = new AuthorizationScope("global", "accessEverything");
		AuthorizationScope[] scopes = new AuthorizationScope[1];
		scopes[0] = scope;
		ArrayList<SecurityReference> list = Lists.newArrayList();
		list.add(new SecurityReference(SecurityConstant.TOKEN, scopes));
		list.add(new SecurityReference(SecurityConstant.LOGIN_TYPE, scopes));
		return list;
	}

	/**
	 * 默认请求头token
	 *
	 * @return 认证列表
	 */
	private List<SecurityScheme> securitySchemes() {
		ArrayList<SecurityScheme> list = Lists.newArrayList();
		list.add(new ApiKey(SecurityConstant.TOKEN, SecurityConstant.TOKEN, "header"));
		list.add(new ApiKey(SecurityConstant.LOGIN_TYPE, SecurityConstant.LOGIN_TYPE, "header"));
		return list;
	}

	//配置swagger信息
	private ApiInfo apiInfo() {
		Contact contact = new Contact("YCL", "不告诉你", "28*******6@qq.com");
		return new ApiInfo("spring cloud 文档",
				"YCL spring cloud",
				"1.0",
				"不告诉你",
				contact,
				"Apache 2.0",
				"http://www.apache.org/licenses/LICENSE-2.0",
				new ArrayList<>()
		);
	}
}

